<template>
  <a-modal class="induction_modal" v-model="visible" :title="title" :confirmLoading="submitLoading" width="1400px"
    :footer="null">
    <a-alert message="下载标准模板，将信息填充后的结果导入即可。红色背景人员为已存在人员，继续提交降覆盖原有人员" type="info" show-icon style="margin-bottom: 10px;" />
    <div style="display: flex;justify-content: space-between;align-items: center;">
      <div>
        <a-select v-model="enterpriseId" @change="enterpriseChange" style="min-width: 200px;margin-right: 10px;">
          <a-select-option v-for="item in enterpriseData" :key="item.enterpriseId">
            {{ item.name }}
          </a-select-option>
        </a-select>
        <a-space>
          签约平台公司:
          <a-switch v-model="isPark" @change="parkSwitch" style="margin-right: 10px;"/>
          <a-select v-if="isPark" v-model="parkId" @change="parkChange" style="width: 200px;margin-right: 10px;" placeholder="服务商">
            <a-select-option v-for="item in parkList" :key="item.parkId">
              {{ item.parkName }}
            </a-select-option>
          </a-select>
        </a-space>
        <a-select v-model="templateId" @change="templateChange" style="width: 200px;" placeholder="协议模板">
          <a-select-option v-for="item in templateData" :key="item.uniqueCode" :name="item.name">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </div>
      <div>
        <a-button type='primary' @click="downloadExcel">下载模板</a-button>
        <a-button type='primary' @click="importOrder" style="margin-left: 10px;">导入表单</a-button>
        <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileExcel"
          @change="importOrderHandle" style="display: none;" />
        <a-button type='primary' style="margin-left: 10px;" @click="addFormSubmit">确认提交</a-button>
        <a-button type='danger' style="margin-left: 10px;" ghost @click="clearTable">清空</a-button>
      </div>
    </div>
    <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination"
      @change="handleTableChange" :rowClassName="tableRowClassName" rowKey="id">
      <!-- 操作栏-->
      <span slot="action" slot-scope="text, record">
        <!-- 编辑模块 | 字段 -->
        <a-popconfirm title="确认删除?" ok-text="确认" cancel-text="取消" @confirm="delTable(record)">
          <a>删除</a>
        </a-popconfirm>
      </span>
    </a-table>
  </a-modal>
</template>

<script>

import store from '@/store'
import OrgTree from "@/components/human/orgTree.vue"
import { mapGetters, mapActions } from 'vuex'
import {
  enterprisePactTemplate,
  previewEnterpriseImportRecord,
  importEnterpriseStaffRecords,
  downloadExcelTemplate,
  submitImportRecord,
  removeImportRecords,
  clearImportRecords
} from "@/api/human/relationInduction"
import {
  parkRelation
} from "@/api/human/ensurePayOrder"
import {
  COLUMNS_INDUCTION_ALL
} from "./form"
export default {
  name: 'AddPark',
  components: {
    OrgTree
  },
  data() {
    return {
      title: "批量添加员工",
      visible: false,
      staffId: "",
      submitLoading: false,

      enterpriseId: '',
      enterpriseData: [], // 企业列表
      templateId: undefined,
      templateName: "",
      templateData: [], // 协议模板
      isPark: false,
      parkId: undefined,
      parkList: [], // 服务商列表

      table: {
        columns: COLUMNS_INDUCTION_ALL,
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      pagination: { current: 1, pageSize: 10 },
    }
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    });
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    // 打开编辑弹窗 
    async add(rows,enterpriseId) {
      this.visible = true;
      if (this.userInfo.type == 4) {
        // hr管理端
        this.getEnterpriseData(enterpriseId);
      } else if (this.userInfo.type == 5) {
        // hr企业端
        this.enterpriseId = enterpriseId;
        this.templateData = templateData;
      }
    },
    //行内颜色
    tableRowClassName(record, index) {
      if (record.redFlag == 1) {
        return 'red'
      }
    },
    // 获取企业员工列表
    async loadTable(flag) {
      let params = {
        enterpriseId: this.enterpriseId
      };
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await previewEnterpriseImportRecord(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    // 下载模板
    downloadExcel() {
      downloadExcelTemplate(this.enterpriseId).then(res => {
        const blob = new Blob([res]);
        const fileName = '员工录入模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      });
    },
    // 导入表单
    importOrder() {
      this.$refs.fileExcel.click();
    },
    importOrderHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("enterpriseId", _this.enterpriseId);
        formData.append("file", file);
        importEnterpriseStaffRecords(formData).then((res) => {
          if (res.code == 1) {
            _this.loadTable(true);
          }
        })
      }
    },
    parkSwitch() {
      if (!this.isPark) {
        this.parkId = undefined;
      }
    },
    // 获取客户员工
    async getEnterpriseData(id) {
      this.enterpriseData = await store.dispatch('department/getAllEnterprise');
      if (id) {
        this.enterpriseId = id;
      } else {
        this.enterpriseId = this.enterpriseData[0].enterpriseId;
      }
      this.loadTable(true);
      this.getTemplateData();
    },
    // 获取服务商列表
    async getParkRelation() {
      const { code, data } = await parkRelation(this.enterpriseId);
      if (code == "1") {
        this.parkList = data;
        this.parkId = this.parkList[0].parkId;
        this.getTemplateData();
      }
    },
    // 选择客户
    enterpriseChange(value) {
      this.enterpriseId = value
      if (this.isPark) {
        this.getParkRelation();
      } else {
        this.getTemplateData();
      }
    },
    // 选择服务商
    parkChange(value) {
      this.parkId = value
      this.getTemplateData();
    },
    // 选择模板
    templateChange(value, option) {
      this.templateId = value
      this.templateName = option.data.attrs.name
    },
    // 获取签约模板列表
    async getTemplateData() {
      this.templateData = [];
      this.templateId = undefined;
      this.templateName = "";
      let { code, data } = await enterprisePactTemplate({ 
        enterpriseId: this.enterpriseId,
        parkId: this.parkId
       });
      if (code == 1) {
        if (data) {
          this.templateData = data
          this.templateId = this.templateData[0].uniqueCode;
          this.templateName = this.templateData[0].name;
        }
      }
    },
    // 提交
    async addFormSubmit() {
      const params = {
        enterpriseId: this.enterpriseId,
        pactTempId: this.templateId,
        pactTempName: this.templateName
      };
      let { code } = await submitImportRecord(params);
      if (code == 1) {
        this.$message.success("操作成功");
        this.visible = false;
        this.$emit('on-ok');
      }
    },
    async clearTable() {
      const params = {
        enterpriseId: this.enterpriseId
      };
      let { code } = await clearImportRecords(params);
      if (code == 1) {
        this.$message.success("操作成功");
        // this.visible = false;
        this.loadTable(true)
      }
    },
    // 删除
    async delTable(rows) {
      let { code } = await removeImportRecords({ ids: [rows.id] });
      if (code == 1) {
        this.$message.success("操作成功");
        // this.visible = false;
        this.loadTable(true)
      }
    }

  }
}
</script>
<style lang="less">
.induction_modal {
  .ant-table-tbody .red{
    background-color: rgba(255, 77, 79, .35);
  }
}
</style>
